package priv.lhy.ecm.service;

import pirv.lhy.ecm.collectorAPI.constants.TableInfo;
import priv.lhy.common.utils.DateUtil;
import priv.lhy.ecm.mapper.AbsMapper;

import java.lang.reflect.ParameterizedType;
import java.util.Date;

/**
 * author: lihy
 * date: 2019/6/26 14:40
 * description:
 */
public abstract class AbsService<T> {

    //private AbsMapper<T> mapper;

    protected String tablePrefix;

    private String companyCode;

    private String indexName;

    private String tableName;

    private final String mapperPackage = "priv.lhy.ecm.mapper";

    //用于检测表存在时加锁
    private static Integer LOCK = 0;

    public AbsService() {
        //this.mapper = mapper;
        //根据传入的泛型类型获取表前缀
        Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
        tablePrefix = TableInfo.tableNamePrefix.get(clazz);

    }


    public void setCompanyCode(String companyCode) {
        this.companyCode = companyCode;
    }

    public String getTableName() {
        return tableName;
    }

    /**
     * 创建表名
     */
    protected void createTableName(String tableSuffix) {
        if (null == tableSuffix || tableSuffix.equals("")) {
            tableSuffix = DateUtil.dateCustomStr(new Date(),"yyyyMM");
        }
        //创建索引名
        this.indexName = "index" + tablePrefix + "_" + companyCode + "_" + tableSuffix;
        //创建表名
        this.tableName = tablePrefix + "_" + companyCode + "_" + tableSuffix;
    }

    /**
     * 表是否存在
     *
     * @return
     */
    private boolean existTable(AbsMapper<T> mapper, String tableSuffix) {
        //加同步锁，防止多线程同步操作
        synchronized (LOCK) {
            createTableName(tableSuffix);
            //先查缓存
            boolean flag = TableInfo.existTable.contains(tableName);
            if (!flag) {
                //缓存没有则查数据库
                flag = mapper.existTable(tableName) == 0 ? false : true;
                //数据库有则存入缓存
                if (flag) {
                    TableInfo.existTable.add(tableName);
                }
            }
            return flag;
        }
    }

    /**
     * 创建表
     */
    protected void createTable(AbsMapper<T> mapper, String tableSuffix) {
        if (!existTable(mapper, tableSuffix)) {
            //表不存在则创建表和索引，并将表名存入缓存
            mapper.createTable(tableName);
            mapper.createIndex(tableName, indexName);
            TableInfo.existTable.add(tableName);
        }
    }

}
